import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { fabric } from 'fabric';

interface ImageState {
  currentImage: string | null;
  originalImage: string | null;
  canvas: HTMLCanvasElement | null;
  fabricCanvas: fabric.Canvas | null;
  isProcessing: boolean;
  history: string[];
  historyIndex: number;
  filters: {
    brightness: number;
    contrast: number;
    saturation: number;
    blur: number;
  };
}

const initialState: ImageState = {
  currentImage: null,
  originalImage: null,
  canvas: null,
  fabricCanvas: null,
  isProcessing: false,
  history: [],
  historyIndex: -1,
  filters: {
    brightness: 0,
    contrast: 0,
    saturation: 0,
    blur: 0,
  },
};

const imageSlice = createSlice({
  name: 'image',
  initialState,
  reducers: {
    setCurrentImage: (state, action: PayloadAction<string>) => {
      state.currentImage = action.payload;
      if (!state.originalImage) {
        state.originalImage = action.payload;
      }
    },
    setOriginalImage: (state, action: PayloadAction<string>) => {
      state.originalImage = action.payload;
    },
    setCanvas: (state, action: PayloadAction<HTMLCanvasElement>) => {
      state.canvas = action.payload;
    },
    setFabricCanvas: (state, action: PayloadAction<fabric.Canvas>) => {
      state.fabricCanvas = action.payload;
    },
    setProcessing: (state, action: PayloadAction<boolean>) => {
      state.isProcessing = action.payload;
    },
    updateFilters: (state, action: PayloadAction<Partial<ImageState['filters']>>) => {
      state.filters = { ...state.filters, ...action.payload };
    },
    resetFilters: (state) => {
      state.filters = initialState.filters;
    },
    addToHistory: (state, action: PayloadAction<string>) => {
      state.history = state.history.slice(0, state.historyIndex + 1);
      state.history.push(action.payload);
      state.historyIndex = state.history.length - 1;
    },
    undo: (state) => {
      if (state.historyIndex > 0) {
        state.historyIndex -= 1;
        state.currentImage = state.history[state.historyIndex];
      }
    },
    redo: (state) => {
      if (state.historyIndex < state.history.length - 1) {
        state.historyIndex += 1;
        state.currentImage = state.history[state.historyIndex];
      }
    },
    resetImage: (state) => {
      state.currentImage = state.originalImage;
      state.filters = initialState.filters;
      state.history = [];
      state.historyIndex = -1;
    },
  },
});

export const {
  setCurrentImage,
  setOriginalImage,
  setCanvas,
  setFabricCanvas,
  setProcessing,
  updateFilters,
  resetFilters,
  addToHistory,
  undo,
  redo,
  resetImage,
} = imageSlice.actions;

export default imageSlice.reducer;